import {PermissionsAndroid, Platform, ToastAndroid} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';
import RNFS from 'react-native-fs';
import {randNum} from './math';

/**
 * 获取文件系统授权
 * @returns boolean
 */
async function hasAndroidPermission() {
  const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
  const hasPermission = await PermissionsAndroid.check(permission);
  if (hasPermission) {
    return true;
  }
  const status = await PermissionsAndroid.request(permission);
  return status === 'granted';
}

/**
 * 文件下载
 * @param {String} url 文件地址
 * @param {String} format 文件格式
 */
export const downloadFile = (url, format = 'jpg') => {
  const fileName = randNum(100000, 999999);
  const downloadDest = `${RNFS.DocumentDirectoryPath}/${fileName}.${format}`;
  const options = {
    fromUrl: url,
    toFile: downloadDest,
    background: true,
  };
  try {
    const ret = RNFS.downloadFile(options);
    ret.promise
      .then(async res => {
        if (Platform.OS === 'android' && !(await hasAndroidPermission())) {
          return false;
        }
        CameraRoll.save(downloadDest)
          .then(() => {
            ToastAndroid.show('图片已保存', ToastAndroid.SHORT);
          })
          .catch(() => {
            ToastAndroid.show('保存失败', ToastAndroid.SHORT);
          });
      })
      .catch(error => {
        ToastAndroid.show(String(error), ToastAndroid.SHORT);
      });
  } catch (error) {
    ToastAndroid.show(String(error), ToastAndroid.SHORT);
  }
};
